const { Router } = require("express");
const Address = require("../model/Address");

const router = new Router();

router.use(require("../middleware/auth.js"));
// 添加用户地址
// http://localhost:8000/api/address/
router.post("/", async (req, res) => {
  const { place, phone, name, openid } = req.body;
  Address.create({ user: openid, place, phone, name });
  res.status(200).json({ message: "添加成功" });
});

// 查询用户地址
router.get("/", async (req, res) => {
  const { openid } = req.body;
  const data = await Address.find().populate(["user"]);
  res.status(200).json({ message: "查询成功", data });
});

// 修改用户地址信息
router.patch("/", async (req, res) => {
  const user = req.userInfo._id;
  const { _id, ...body } = req.body;
  console.log(body);
  const data = await Address.findOneAndUpdate({ _id, user }, { body });
  res.status(200).json({ message: "修改成功", data });
});

// 删除用户地址
router.delete("/", async (req, res) => {
  const user = req.userInfo._id;
  const { _id } = req.body;
  const data = await Address.findOneAndDelete({ user, _id });
  res.status(200).json({ message: "删除成功", data });
});

module.exports = router;
